package com.hliushi.exception;

import com.google.common.collect.ImmutableMap;
import com.hliushi.response.CommonCode;
import com.hliushi.response.ResponseResult;
import com.hliushi.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @ClassName ExceptionCatch
 * @Description 统一异常捕获类
 * @Author liushi
 * @Date 2020/7/15 21:56
 * @Version V1.0
 **/
//控制器增强
// @ControllerAdvice
public class ExceptionCatch {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);
    //定义map的builder对象,去构建ImmutableMap
    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();
    //定义map,配置异常类型所对应的错误代码
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;

    static {
        //定义异常类型所对应的错误代码
        builder.put(HttpMessageNotReadableException.class, CommonCode.UNEXCEPTION_EXCEPTION);
    }


    // 捕获BusinessErrorException此类异常
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseBody
    public ResponseResult customException(BusinessErrorException customException) {
        // 把错误信息打印出来
        customException.printStackTrace();
        //记录日志
        LOGGER.error("catch exception:{}", customException.getMessage());
        ResultCode resultCode = customException.getResultCode();
        return new ResponseResult(resultCode);
    }

    // 捕获Exception此类异常
    @ExceptionHandler(Exception.class)
    @ResponseBody  //将java对象错误信息转换为json
    public ResponseResult exception(Exception exception) {
        // 把错误信息打印出来
        exception.printStackTrace();
        //记录日志
        LOGGER.error("catch exception:{}", exception.getMessage());
        if (EXCEPTIONS == null) {
            //EXCEPTIONS构建成功
            EXCEPTIONS = builder.build();
        }
        // 从EXCEPTIONS中找异常类型所对应的错误代码,如果找到了将错误代码响应给用户,如果找不到给用户响应99999
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode != null) {
            return new ResponseResult(resultCode);
        } else {
            //返回99999异常状态码
            return new ResponseResult(CommonCode.UNEXCEPTION_EXCEPTION);
        }
    }
}
